<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  getGoodsList,
  deleteGoods,
  updateGoods,
  getTypeList,
  addType,
  updateType,
  deleteType,
  addGoods,
} from '#/api/core/goods';
import type { VbenFormProps } from '@vben/common-ui';
import { ElButton, ElMessage, ElMessageBox } from 'element-plus';
import { useVbenForm } from '#/adapter/form';
import { useVbenDrawer } from '@vben/common-ui';
import { ref, reactive, onMounted } from 'vue';
import { Folder, Plus, Edit, Delete, Picture } from '@element-plus/icons-vue';
import { getstoreList } from '#/api/core/store';
import { useAccessStore } from '@vben/stores';

const [Drawer, drawerApi] = useVbenDrawer({
  title: '编辑商品',
  footer: false,
});

interface RowType {
  id: number;
  name: string;
  price: number;
  num: number;
  tid: number;
  img: string;
  details: string;
  createdAt: string;
  updatedAt: string;
}
function formatToken(token: null | string) {
  return token ? `${token}` : null;
}

// 1. 首先定义所有的 ref 和响应式数据
/**
 * 获取商品列表数据
 */
function getTableData(params: { page: any; size: any; name?: string }) {
  return new Promise<{ items: any; total: number }>((resolve) => {
    const { page, size, name } = params;
    getGoodsList({
      page,
      pageSize: size,
      name,
    }).then((res) => {
      resolve({
        total: res.data.total,
        items: res.data.list,
      });
    });
  });
}

const fileListIcon = ref([]);
const editData = ref({
  img: '',
});
const addGoodsVisible = ref(false);
const typeDialogVisible = ref(false);
const typeFormRef = ref();
const editingType = ref(null);
const typeList = ref([]);
const storeList = ref([]);
const showTypeList = ref(true);
const goods = ref({
  id: 0,
  name: '',
  price: 0,
  num: 0,
  tid: 0,
  img: '',
  details: '',
});

// 2. 定义表单提交方法
const onSubmit = async (values: Record<string, any>) => {
  try {
    values.img = editData.value.img;
    if (goods.value.id) {
      // 编辑
      await updateGoods({
        id: goods.value.id,
        ...values,
      });
      ElMessage.success('修改成功');
      drawerApi.close();
    } else {
      // 新增
      await addGoods(values);
      ElMessage.success('添加成功');
      addGoodsVisible.value = false;
    }
    gridApi.query(); // 刷新列表
  } catch (error) {
    console.error('保存商品失败：', error);
    ElMessage.error('保存失败');
  }
};

// 3. 定义商品表单配置
const [Formgoods, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  handleSubmit: onSubmit,
  layout: 'horizontal',
  schema: [
    {
      component: 'VbenSelect',
      componentProps: {
        placeholder: '请选择商品分类',
        options: typeList,
        fieldNames: {
          label: 'typename',
          value: 'id',
        },
      },
      fieldName: 'tid',
      label: '商品分类',
      rules: 'required',
    },
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '请输入商品名称',
      },
      fieldName: 'name',
      rules: 'required',
      label: '商品名称',
    },
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '请输入价格',
        min: 0,
        precision: 2,
      },
      fieldName: 'price',
      rules: 'required',
      label: '价格',
    },
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '请输入库存',
        min: 0,
        precision: 0,
      },
      fieldName: 'num',
      rules: 'required',
      label: '库存',
    },
    {
      component: 'Upload',
      componentProps: {
        placeholder: '请上传商品图片',
        listType: 'picture-card',
        limit: 1,
      },
      fieldName: 'image',
      label: '商品图片',
    },
    {
      component: 'VbenInput',
      componentProps: {
        type: 'textarea',
        placeholder: '请输入商品详情',
        rows: 4,
      },
      fieldName: 'details',
      label: '商品详情',
    },
  ],
  wrapperClass: 'grid-cols-1',
});

// 4. 定义获取数据的方法
const fetchTypeList = async () => {
  try {
    const res = await getTypeList({
      page: 1,
      size: 999,
    });
    typeList.value = res.data.list;
  } catch (error) {
    console.error('获取分类列表失败：', error);
    ElMessage.error('获取分类列表失败');
  }
};

const fetchStoreList = async () => {
  try {
    const res = await getstoreList({
      page: 1,
      size: 999,
      storeName: '',
    });
    storeList.value = res.data.list || [];
  } catch (error) {
    ElMessage.error('获取门店列表失败');
  }
};

// 3. 定义提交方法
const submitTypeForm = async (values: Record<string, any>) => {
  if (!values.storeId) {
    ElMessage.warning('请选择门店');
    return;
  }

  try {
    if (editingType.value) {
      await updateType({
        ...values,
        id: editingType.value.id,
      });
      ElMessage.success('修改成功');
    } else {
      await addType(values);
      ElMessage.success('添加成功');
    }
    typeDialogVisible.value = false;
    fetchTypeList();
  } catch (error) {
    console.error('保存分类失败：', error);
    ElMessage.error('保存失败');
  }
};

// 4. 定义表单配置
const typeFormOptions = {
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  handleSubmit: submitTypeForm,
  layout: 'horizontal',
  schema: [
    {
      component: 'VbenSelect',
      componentProps: {
        placeholder: '请选择门店',
        options: storeList,
        fieldNames: {
          label: 'storeName',
          value: 'id',
        },
        teleported: true,
      },
      fieldName: 'storeId',
      label: '所属门店',
      rules: 'required',
    },
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '请输入分类名称',
      },
      fieldName: 'name',
      rules: 'required',
      label: '分类名称',
    },
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入排序',
        min: 0,
        controlsPosition: 'right',
      },
      fieldName: 'order',
      label: '排序',
    },
  ],
  wrapperClass: 'grid-cols-1',
};

// 4. 初始化表单实例
const [TypeForm, typeFormApi] = useVbenForm(typeFormOptions);

// 4. 定义表格配置
const gridOptions: VxeGridProps<RowType> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  pagerConfig: {
    pageSizes: [10, 20, 50],
  },
  columns: [
    { title: '序号', type: 'seq', width: 50 },
    { align: 'left', title: '商品名称', field: 'name' },
    { align: 'left', title: '商品分类', field: 'typename' },

    { field: 'price', title: '商品价格' },
    { field: 'num', title: '品库存' },
    { field: 'img', title: '商品图片', slots: { default: 'img' } },
    { field: 'details', title: '商品详情' },

    {
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      title: '操作',
      width: 120,
    },
  ],
  exportConfig: {},
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        return await getTableData({
          page: page.currentPage,
          size: page.pageSize,
          ...formValues,
        });
      },
    },
  },
  toolbarConfig: {
    custom: true,
    export: true,
    refresh: true,
    zoom: true,
  },
};

const formOptions: VbenFormProps = {
  collapsed: false,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '输入商品名称',
      },
      defaultValue: '',
      fieldName: 'name',
      label: '商品名称',
    },
  ],
  showCollapseButton: false,
  submitButtonOptions: {
    content: '查询',
  },
  submitOnEnter: false,
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
  formOptions,
});

const open = (row: RowType) => {
  goods.value = { ...row };
  formApi.setValues(goods.value);
  editData.value.img = row.img;
  drawerApi.open();
};

// 处理添加商品按钮点击
const handleAdd = () => {
  formApi.setValues({
    name: '',
    price: 0,
    num: 0,
    tid: '',
    img: '',
    details: '',
  });
  editData.value.img = '';
  fileListIcon.value = [];
  addGoodsVisible.value = true;
};

const del = (data: { id: number }) => {
  ElMessageBox.confirm('此操作将永久删除该商品, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteGoods(data.id).then(() => {
      ElMessage.success('删除成功');
      gridApi.query();
    });
  });
};

// 修改 openTypeDialog 方法
const openTypeDialog = (type = null, showList = true) => {
  editingType.value = type;
  showTypeList.value = showList;
  if (type) {
    type.name = type.typename;
    typeFormApi.setValues(type);
  } else {
    typeFormApi.setValues({
      name: '',
      order: 0,
      storeId: '',
    });
  }
  typeDialogVisible.value = true;
};

// 删除分类
const handleDeleteType = (type) => {
  ElMessageBox.confirm('确定要删除该分类吗？删除后不可恢复！', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await deleteType(type.id);
      ElMessage.success('删除成功');
      fetchTypeList();
    } catch (error) {
      console.error('删除分类失败：', error);
      ElMessage.error('删除失败');
    }
  });
};

// 添加上传相关的变量和方法
const accessStore = useAccessStore();

// 上传前的验证
const beforeAvatarUploadicon = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
};

// 上传成功的回调
const changeIcon = (response: any) => {
  if (response.code === 200) {
    editData.value.img = response.data.url;
    formApi.setValues({
      img: response.data,
    });
  }
};

// 移除图片的回调
const handleRemoveicon = () => {
  editData.value.img = '';
  formApi.setValues({
    img: '',
  });
};

// 在页面加载时获取门店列表
onMounted(() => {
  fetchStoreList();
  fetchTypeList();
});
</script>

<template>
  <div class="vp-raw w-full">
    <Grid>
      <template #toolbar-tools>
        <div class="header-actions flex items-center justify-between">
          <div class="left-actions">
            <el-button type="primary" @click="openTypeDialog(null, true)">
              <template #icon>
                <el-icon><Folder /></el-icon>
              </template>
              分类管理
            </el-button>
            <el-button type="success" @click="handleAdd">
              <template #icon>
                <el-icon><Plus /></el-icon>
              </template>
              新增商品
            </el-button>
          </div>
        </div>
      </template>
      <template #img="{ row }">
        <el-image
          style="width: 100px; height: 100px"
          :src="row.img"
          fit="cover"
          :preview-src-list="[row.img]"
          class="goods-image"
        >
          <template #error>
            <div class="image-placeholder">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-image>
      </template>
      <template #action="{ row }">
        <el-button type="primary" link @click="open(row)"> 编辑 </el-button>
        <el-button type="danger" link @click="del(row)"> 删除 </el-button>
      </template>
    </Grid>

    <!-- 分类管理弹窗 -->
    <el-dialog
      v-model="typeDialogVisible"
      :title="showTypeList ? '分类管理' : editingType ? '编辑分类' : '新增分类'"
      :width="showTypeList ? '1000px' : '600px'"
      destroy-on-close
      append-to-body
    >
      <div class="p-4">
        <!-- 新增/编辑表单 -->
        <template v-if="!showTypeList">
          <TypeForm class="mb-6">
            <template #storeId="slotProps">
              <el-select
                v-bind="slotProps"
                placeholder="请选择门店"
                style="width: 100%"
              >
                <el-option
                  v-for="item in storeList"
                  :key="item.id"
                  :label="item.store_name"
                  :value="item.id"
                />
              </el-select>
            </template>
          </TypeForm>
        </template>

        <!-- 分类列表 -->
        <template v-else>
          <div class="mb-4 flex items-center justify-between">
            <h3 class="text-lg font-medium">分类列表</h3>
            <el-button type="primary" @click="openTypeDialog(null, false)">
              <template #icon>
                <el-icon><Plus /></el-icon>
              </template>
              新增分类
            </el-button>
          </div>

          <div class="type-list">
            <el-table :data="typeList" border style="width: 100%">
              <el-table-column
                prop="order"
                label="排序"
                width="100"
                align="center"
              />
              <el-table-column prop="typename" label="分类名称" />

              <el-table-column prop="StoreName" label="所属门店" />
              <el-table-column label="操作" width="160" align="center">
                <template #default="{ row }">
                  <el-button
                    type="primary"
                    link
                    @click="openTypeDialog(row, false)"
                  >
                    编辑
                  </el-button>
                  <el-button type="danger" link @click="handleDeleteType(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <div v-if="!typeList.length" class="empty-type">
              <el-empty description="暂无分类数据" />
            </div>
          </div>
        </template>
      </div>
    </el-dialog>

    <!-- 添加商品对话框 -->
    <el-dialog
      v-model="addGoodsVisible"
      title="新增商品"
      width="600px"
      destroy-on-close
      append-to-body
    >
      <div class="p-4">
        <Formgoods>
          <template #tid="slotProps">
            <el-select
              v-bind="slotProps"
              placeholder="请选择商品分类"
              style="width: 100%"
            >
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item.typename"
                :value="item.id"
              />
            </el-select>
          </template>
          <template #image="">
            <el-upload
              class="upload-demo"
              v-model:file-list="fileListIcon"
              drag
              :on-success="changeIcon"
              action="/v1/upload"
              :show-file-list="true"
              :on-remove="handleRemoveicon"
              :headers="{ authorization: formatToken(accessStore.accessToken) }"
              :before-upload="beforeAvatarUploadicon"
            >
              <img v-if="editData.img" :src="editData.img" class="avatar" />
              <el-icon class="el-icon--upload" v-else>
                <Plus />
              </el-icon>
            </el-upload>
          </template>
        </Formgoods>
      </div>
    </el-dialog>

    <Drawer class="w-[800px]" ref="drawer">
      <Formgoods>
        <template #tid="slotProps">
          <el-select
            v-bind="slotProps"
            placeholder="请选择商品分类"
            style="width: 100%"
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.typename"
              :value="item.id"
            />
          </el-select>
        </template>
      </Formgoods>
    </Drawer>
  </div>
</template>

<style scoped>
.type-list {
  margin-top: 20px;
  max-height: 400px;
  overflow-y: auto;
}

:deep(.upload-demo) {
  .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration);
    width: 146px;
    height: 146px;

    &:hover {
      border-color: var(--el-color-primary);
    }
  }

  .el-upload-dragger {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .avatar {
    width: 100%;
    height: 100%;
    display: block;
    object-fit: cover;
  }

  .el-icon--upload {
    font-size: 28px;
    color: #8c939d;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

/* 添加上传列表样式 */
:deep(.el-upload-list--picture-card) {
  --el-upload-list-picture-card-size: 146px;
}

/* 添加拖拽区域样式 */
:deep(.el-upload-dragger) {
  width: 146px;
  height: 146px;
  padding: 0;
}
</style>
